<?php

namespace Shared;

/**
 * @abstract
 * 
 * @author Peter Yordanov <p.jordanov@object.bg>
 * @copyright (c) 2014, ASPECT.BG Ltd. (http://www.aspect.bg/)
 */
abstract class EntityUtils {

	/**
	 * @static
	 * 
	 * @return \Cornerstone\EntityManager
	 */
	private static function getEntityManager() {
		return Application::instance()->getEntityManager();
	}

	/**
	 * @static
	 * 
	 * @param string $rootEntity
	 * @param string $disriminatorMapId
	 * @return string
	 * @throws \Exception
	 */
	public static function getEntityFQCNByDiscriminatorMapId($rootEntity, $disriminatorMapId) {
		$em = self::getEntityManager();

		$metadata = $em->getClassMetadata($rootEntity);

		if (!array_key_exists($disriminatorMapId, $metadata->discriminatorMap)) {
			throw new \Exception(sprintf('could not find discriminator value %s for class %s', $disriminatorMapId, $rootEntity));
		}

		return $metadata->discriminatorMap[$disriminatorMapId];
	}

	/**
	 * @static
	 * 
	 * @param string $entityInstanceOrFqcn
	 * @return string
	 */
	public static function getEntityDiscriminatorMapId($entityInstanceOrFqcn) {
		$em = self::getEntityManager();

		$metadata = $em->getClassMetadata(self::getEntityFQCN($entityInstanceOrFqcn));

		return $metadata->discriminatorValue;
	}

	public static function getEntityFQCN($entityInstanceOrFqcn) {
		if (is_object($entityInstanceOrFqcn)) {
			return \Doctrine\Common\Util\ClassUtils::getClass($entityInstanceOrFqcn);
		}
		return \Doctrine\Common\Util\ClassUtils::getRealClass($entityInstanceOrFqcn);
	}

}
